#!/bin/sh
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

### BEGIN INIT INFO
# Provides:          chameleond
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start chameleond at boot time
# Description:       Enable service provided by chameleond for remote
#                    controlling the Chameleon board.
### END INIT INFO

DAEMON_NAME='chameleond'
CONFIG_FILE="/etc/default/${DAEMON_NAME}"
. "${CONFIG_FILE}"

DAEMON="${CHAMELEOND_DIR}/run_chameleond"
DAEMON_ARGS="--driver ${CHAMELEON_BOARD}"
DAEMON_USER='root'
PIDFILE="/var/run/${DAEMON_NAME}.pid"

is_already_running () {
    start-stop-daemon --stop --test --quiet --pidfile "${PIDFILE}"
}

is_ip_found () {
    ip addr | grep inet | grep eth0 > /dev/null
}

do_start () {
    if ! is_ip_found; then
        echo "No IP found, try to restart network..."
        /etc/init.d/networking restart
    fi

    if ! is_already_running; then
        start-stop-daemon --start --background --pidfile "${PIDFILE}" \
            --make-pidfile --user "${DAEMON_USER}" --chuid "${DAEMON_USER}" \
            --startas "${DAEMON}" -- ${DAEMON_ARGS}
        do_status
    else
        echo "${DAEMON_NAME} is already running."
    fi
}

do_stop () {
    if is_already_running; then
        start-stop-daemon --stop --pidfile "${PIDFILE}" --retry 10
        rm -f "${PIDFILE}"
    else
        echo "${DAEMON_NAME} is already stopped"
    fi
}

do_status () {
    is_already_running &&
        echo "${DAEMON_NAME} is running." ||
        echo "${DAEMON_NAME} is not running"
}

case "$1" in
    start|stop|status)
        do_${1}
        ;;

    restart)
        do_stop
        do_start
        ;;

    *)
        echo "Usage: /etc/init.d/${DAEMON_NAME} {start|stop|restart|status}"
        exit 1
        ;;
esac
exit 0
